package hhh.app.common.rxjava;

import android.accounts.NetworkErrorException;

import hhh.app.common.error.NetworkConnectionException;
import hhh.app.common.error.ServerException;
import hhh.app.data.bean.MyResult;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by hhh on 2016/12/9.
 */
public class RxResultHelper {
    public static <U> Observable.Transformer<MyResult<U>,U> handleResult(){
        return new Observable.Transformer<MyResult<U>, U>() {
            @Override
            public Observable<U> call(Observable<MyResult<U>> myResultObservable) {
                return myResultObservable.flatMap(new Func1<MyResult<U>, Observable<U>>() {
                    @Override
                    public Observable<U> call(MyResult<U> uMyResult) {
                        if(uMyResult==null){
                            return Observable.error(new NetworkConnectionException());
                        }else if(uMyResult.code==MyResult.STATE_SUC){
                            return createData(uMyResult.data);
                        }else {
                            return Observable.error(new ServerException(uMyResult.code,uMyResult.message));
                        }
                    }
                });
            }
        };
    }

    private static <U> Observable<U> createData(final U data) {
        return Observable.create(new Observable.OnSubscribe<U>() {
            @Override
            public void call(Subscriber<? super U> subscriber) {
                try {
                    subscriber.onNext(data);
                    subscriber.onCompleted();
                }catch (Exception e){
                    subscriber.onError(e);
                }

            }
        });
    }
}
